package cn.edu.nju.software.service.impl;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.nju.software.bean.show.CommentSearchListItem;
import cn.edu.nju.software.bean.storage.Comment;
import cn.edu.nju.software.dao.intf.CommentDao;
import cn.edu.nju.software.service.intf.CommentService;
import cn.edu.nju.software.util.Constants;

public class CommentServiceImpl implements CommentService {
	
	private CommentDao commentDao;

	public void setCommentDao(CommentDao commentDao) {
		this.commentDao = commentDao;
	}

	@Override
	public void postComment(int userID, int bookID, String content) throws SQLException {
		commentDao.postComment(new Comment(0, userID, bookID, content, new Timestamp(System.currentTimeMillis()), null));
	}

	@Override
	public List<CommentSearchListItem> getCommentByBookID(int bookID) throws SQLException {
		return commentDao.getCommentByBookID(bookID);
	}

	@Override
	public List<CommentSearchListItem> searchComments(String user, String bookTitle, Date beginDate, Date endDate) throws SQLException {
		Map<Integer, Object> criteria = new HashMap<Integer, Object>();
		if (user != null && !user.equals("")) {
			criteria.put(Constants.SEARCH_USER, user);
		}
		if (beginDate != null || endDate != null) {
			if (beginDate == null) {
				beginDate = new Date(Long.MIN_VALUE);
			}
			if (endDate == null) {
				endDate = new Date(Long.MAX_VALUE);
			}
			List<Date> date = new ArrayList<Date>(2);
			date.add(beginDate);
			date.add(endDate);
			criteria.put(Constants.SEARCH_DATE, date);
		}
		if (bookTitle != null && !bookTitle.equals("")) {
			criteria.put(Constants.SEARCH_TITLE, bookTitle);
		}
		return commentDao.searchComments(criteria);
	}

	@Override
	public void modifyCommentStatus(int commentID, int operateCode) throws SQLException {
		switch (operateCode) {
		case Constants.GOTO_TOP:
			commentDao.updateComment(new Comment(commentID, 0, 0, null, null, new Timestamp(System.currentTimeMillis())));
			break;
		case Constants.CANCEL_TOP:
			commentDao.updateComment(new Comment(commentID, 0, 0, null, null, null));
			break;
		}
	}

}
